#include "data_acquisation_serial.h"
#include     <stdio.h>      /*标准输入输出定义*/
#include     <stdlib.h>     /*标准函数库定义*/
#include     <unistd.h>     /*Unix 标准函数定义*/
#include     <sys/types.h>
#include     <sys/stat.h>
#include     <fcntl.h>      /*文件控制定义*/
#include     <termios.h>    /*PPSIX 终端控制定义*/
#include     <errno.h>      /*错误号定义*/
#include     "main.h"
//0000 00 0x    0x     加水 0
//0000 01 0x    0(4+x) 加热 4
//0000 10 0x    0(8+x) 进气 8
//0000 11 0x    0(C+x) 排气
//0001 00 0x    1x     真空泵
//0001 01 0x    1(4+x) 回气
//0001 10 0x    1(8+x) 开前门
//0001 11 0x    1(C+x) 关前门
//0010 00 0x    2x     前充气
//0010 01 0x    2(4+x) 前排气
//0010 10 0x    2(8+x) 开后门
//0010 11 0x    2(C+x) 关后门
//0011 00 0x    3x     后充气
//0011 01 0x    3(4+x) 后排气
//0011 10 0x    3(8+x) 报警
//0011 11 0x    3(C+x) 运行灯
//0100 00 0x    4x     完成灯
//0100 01 0x    4(4+x)     通信正常指示灯

data_acquisation::data_acquisation(QObject *parent) :
    QThread(parent)
{
    COM_SETUP(tty3_fd,COM3);
    ttyfile.setFileName(COM3);
    if (!ttyfile.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        perror("COM2 open failed !");
    }
    read_data();
    cmd_send_err=false;
    PSU_buf=0;
    PSU_adjust=0;
    TEM_buf=0;
    TEM_adjust=0;
    next_read_num=9;
    IO_bitarray.resize(16);
    count1=0;
    count2=0;
}

data_acquisation::~data_acquisation()
{
    close(tty3_fd);
}

void data_acquisation::stop()
{
    terminate();
}

void data_acquisation::read_data()
{
  if(sensor_data_changed)
   {
    positive_pressure_adjust=sensor_adjust_datamap[trUtf8("1正压")];
    negative_pressure_adjust=sensor_adjust_datamap[trUtf8("2负压")];
    normal_pressure_adjust=  sensor_adjust_datamap[trUtf8("3常压")];
    high_temperature_adjust= sensor_adjust_datamap[trUtf8("温度>130")];
    low_temperature_adjust=  sensor_adjust_datamap[trUtf8("温度<120")];
    mid_temperature_adjust=  sensor_adjust_datamap[trUtf8("温度121~130")];
    average_temperature_adjust=(high_temperature_adjust+mid_temperature_adjust+low_temperature_adjust)/3;
    bottom_door_Sealing_strip_Exhaust_time_ms=sensor_adjust_datamap[trUtf8("下排式胶条抽气时间")]*1000;
    vacuum_door_Sealing_strip_Exhaust_time_ms=sensor_adjust_datamap[trUtf8("真空式胶条抽气时间")]*1000;

    sensor_data_changed=false;
    }
}

inline void data_acquisation::append(uchar c2)
{

    AD_VALUE[c2][count2]='\0';
    count2=0;
    if(AD_VALUE[c2][0]=='-')
    {
         uint size=strlen(AD_VALUE[c2]) -1;
         for(uint i=0;i<size;i++){AD_VALUE[c2][i]=AD_VALUE[c2][i+1];}
         AD_VALUE[c2][size]='\0';
         ad_value[c2]= 0 - atoi(AD_VALUE[c2]);
    }
    else ad_value[c2]= atoi(AD_VALUE[c2]) ;
}

void data_acquisation::run()
{



    while(1)
    {
       // msleep(50);
        if(light)  {LED2_OFF;light=0;}
        else   {LED2_ON;light=1;}

     if(!test_mode)
     {
      read_data();

      if(whole_machine_parameter.IO_drive_type)
     {

        readinput();
        command_output();
      }
       else old_read_ad();

      }

    }
}

void data_acquisation::readinput()
{

//bytearray=QByteArray::fromRawData(buf,read_in_num);
    bytearray=ttyfile.read(next_read_num);
    command_start_addr=bytearray.indexOf('*');
    next_read_num=9;
    if(command_start_addr==-1) return;
    else if(command_start_addr==0)
    {
      if(bytearray[1]=='#'&&bytearray[8]=='#')
      {
          input_data=bytearray[i+2]<<8+bytearray[i+3];
          TEM_buf=bytearray[i+4]<<8+bytearray[i+5];
          PSU_buf=bytearray[i+6]<<8+bytearray[i+7];
          if(input_data==0 && TEM_buf==0 && PSU_buf==0) cmd_send_err=true;//发送数据错误标识
          else
          {
              cmd_send_err=false;
              IO_input_process();
              AD_value_compensate();

          }
      }
    }
    else next_read_num=command_start_addr;
}


void data_acquisation::command_output()
{

    if(cmd_send_err) ttyfile.write(cmd_array);
    else {

            if(!command_queue.isEmpty())//访问空队列出错？
            {
            cmd_code_pair=command_queue.dequeue();
            cmd_array[0]=cmd_code_pair.first;
            if(cmd_code_pair.second) cmd_array[0]+=1;
            cmd_array[1]=~cmd_array[0];
            ttyfile.write(cmd_array);
            }
        }


}


void data_acquisation::old_read_ad()
{

    read_in_num= read(tty3_fd, buf, next_read_num);

   for(i=0;i<read_in_num;i++)
{
 switch(buf[i])
{
case ('T')://校验和S=T+P

     if(!whole_machine_parameter.ad_checksum || ad_value[2]==ad_value[0]+ad_value[1])
    {
        TEM_buf=ad_value[0];
        PSU_buf=ad_value[1];

        AD_value_compensate();

     }

     append(count1);//S结尾
     count1=0;
   break;
case ('P'):
    append(0);//T结尾
    count1=1;
   break;
case ('S'):
      append(1);//P结尾
      count1=2;
      break;
default:
     /****
接收引脚悬空，导致接收非法数据
串口读取数据出错，导致程序崩溃。*********/
     AD_VALUE[count1][count2]=buf[i];
     if(++count2==8) count2=0;//数据不匹配时清零，防止数组溢出
   break;

 }
}

}


void data_acquisation::AD_value_compensate()
{

           if(sterilization_temperature>=130)
             {
               TEM_adjust=high_temperature_adjust;
             }
             else if(120<sterilization_temperature<130)
             {
               TEM_adjust=mid_temperature_adjust;
             }
             else if(sterilization_temperature<=120)
             {
             TEM_adjust=low_temperature_adjust;
             }
             else  TEM_adjust=average_temperature_adjust;

           if(PSU_buf>20) PSU_adjust=positive_pressure_adjust;
           else if(PSU_buf<-20)  PSU_adjust=negative_pressure_adjust;
           else PSU_adjust=normal_pressure_adjust;

           TEM= (float)((TEM_buf+TEM_adjust)*0.1);
           PSU=PSU_buf+PSU_adjust;

           // qDebug()<<TEM<<PSU;
          //  textbrowser->setText("T" +QString::number(TEM) +" P" + QString::number(PSU) );
}


void data_acquisation::IO_input_process()
{

    for(int i=0;i<16;i++)
    {
     IO_bitarray[i]=input_data&(0x0001<<i);
    }

    bottom_water_level_isreached=IO_bitarray[0];//下水位
    top_water_level_isreached=IO_bitarray[1];//上水位
    water_switch_isopen=IO_bitarray[2];//GPC0//水流开关
    inter_pressure_switch_isreached=IO_bitarray[3];//夹层压力开关
    front_door_closed_in_place=IO_bitarray[4];//GPC2
    front_door_opened_in_place=IO_bitarray[5];//GPC3
    front_door_Sealing_strip_pressure_in_place=IO_bitarray[6];// GPN6
    back_door_opened_in_place=IO_bitarray[7];//GPN9
    back_door_closed_in_place=IO_bitarray[8];//GPN11
    back_door_Sealing_strip_pressure_in_place=IO_bitarray[9];// GPL8
    overpressure_protection_switch_isreached=IO_bitarray[10];

}
